﻿using Dealin.Code;
using Dealin.Data.Extensions;
using Dealin.Domain._03_Entity.PublicManage;
using Dealin.Domain.Entity.DeviceManage;
using Dealin.Domain.IRepository.DeviceManage;
using Dealin.Repository.DeviceManage;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Dealin.Application.DeviceManage
{
    public  class MeterApp
    {
        private IMeterRepository service = new MeterRepository(); 
        public DapperDbHelper db = new DapperDbHelper();

        public List<MeterEntity> GetList(string keyword = "")
        {
            var expression = ExtLinq.True<MeterEntity>();
            if (!string.IsNullOrEmpty(keyword))
            {
                var intKeyword = 0;
                try
                {
                    intKeyword = Convert.ToInt32(keyword);
                    expression = expression.And(t => t.F_Port==(intKeyword));
                    expression = expression.Or(t => t.F_Add485==(intKeyword));
                }
                catch  
                { 
                }
            }
            return service.IQueryable(expression).OrderBy(t => t.F_Port&t.F_Add485).ToList();
        }
        public List<Select2> GetSelectItemByOrgID(string orgId,string typeId)
        {

            string proc = string.Format("exec Proc_GetMeterItems_ByOrgId '{0}','{1}'", orgId, typeId);
            //id text
            var list = db.QueryList<Select2>(proc, null);

            return list.ToList();
        }

        public List<MeterEntity> GetListOffLine(string keyword = "")
        {
            var expression = ExtLinq.True<MeterEntity>();
            if (!string.IsNullOrEmpty(keyword))
            {
                var intKeyword = 0;
                try
                {
                    intKeyword = Convert.ToInt32(keyword);
                    expression = expression.And(t => (bool)t.F_IsOnLine == false);
                    expression = expression.And(t => t.F_Port == (intKeyword));
                    expression = expression.Or(t => t.F_Add485 == (intKeyword));
                }
                catch
                {
                }
            }
            return service.IQueryable( expression).OrderBy(t => t.F_Port & t.F_Add485).ToList();
        }

        public MeterEntity GetForm(string keyValue)
        {
            return service.FindEntity(keyValue);
        }
        public void DeleteForm(string keyValue)
        {

            service.Delete(t => t.F_Id == keyValue);
        }
        public void SubmitForm(MeterEntity meterEntity, string keyValue)
        {
            if (!string.IsNullOrEmpty(keyValue))
            {
                meterEntity.Modify(keyValue);
                service.Update(meterEntity);
            }
            else
            {
                meterEntity.Create();
                service.Insert(meterEntity);
            }
        }
    }
}
